package itdfq.dfq.Behavior_Patters.observe;

import java.util.ArrayList;

/**
 * @Author GocChin
 * @Date 2021/5/23 13:33
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Descript:
 */
public class ConcreteSubject implements Subject {
    // 存放观察者列表
    private final ArrayList<Observer> observerList;
    // 被观察的具体信息
    private Boolean changed;
    private Object message;

    ConcreteSubject() {
        observerList = new ArrayList<>();
        changed = false;
        message = "";
    }

    @Override
    public void addObserver(Observer observer) {
        if (!observerList.contains(observer)) {
            this.observerList.add(observer);
        }
    }

    @Override
    public void deleteObserver(Observer observer) {
        if (observerList.contains(observer)) {
            this.observerList.remove(observer);
        }
    }

    @Override
    public void notifyObserver() {
        if (changed) {
            for (Observer observer : observerList) {
                observer.update(message);
            }
        } else {
            System.out.println("没有新信息，不需要通知");
        }
    }

    // 更新
    public void pushNewMessage(Object newMessage) {
        if (!this.message.equals(newMessage)) {
            this.message = newMessage;
            changed = true;
        } else {
            System.out.println("没有信息需要更新");
            changed = false;
        }
    }
}
